<?php namespace App\Admin\Auth;

use Input, Auth, Request;
//基础条件
use App\Core\Repository\Criterias\FixedCriteria;

use App\Admin\Access\User\Repository as UserRepository;

trait LoginService {
    
    //基础服务
    use \App\Core\Service\Service;
    
    protected function bootService(){
        $this->bootBaseService();
    }
    
    //登录
	public function index(){
		return view('admin.login');
	}
    
    //登录
	public function login(){
		//参数
		$username = Input::get('username', '');
		$password = Input::get('password', '');
		$remember = Input::get('remember', '');
		if(empty($username) || empty($password)){
			return $this->inputError('用户名和密码不能为空');
		}
		$user = $this->getUserByUsername($username);
		if(empty($user)){
			return $this->inputError('用户名不存在');
		}
		if($user->islocked == '1' && (time() - $user->login_locked_time) < 1800){
			return $this->inputError('此用户被锁定');
		}
		if(md5($password.$user->saltcode) == $user->password){//验证密码成功
			//解锁用户
			$user->login_error_count = '0';
			$user->login_locked_time = '0';
			$user->islocked = '0';
			//设置登录信息
			$user->last_login_time = $user->current_login_time;
			$user->last_login_ip = $user->current_login_ip;
			$user->current_login_time = time();
			$user->current_login_ip = Request::getClientIp();
			$user->save();
			Auth::login($user, $remember);
			return $this->success('登录成功');
		}else{//验证密码失败
			if($user->login_error_count == '0'){//第一次非正常登录计时开始
				$user->login_locked_time = time();
			}
			//登录错误次数限制
			if((time() - $user->login_locked_time) > 1800){//时间超过30分钟，自动解锁用户
				$user->login_error_count = '0';
				$user->login_locked_time = '0';
				$user->islocked = '0';
				$user->save();
			}else{
				$user->login_error_count = $user->login_error_count +1;
				if($user->login_error_count >9){
					$user->islocked = '1';
					$user->login_locked_time = time();
				}
				$user->save();
			}
			return $this->inputError('密码错误，还有'.(10 - $user->login_error_count).'次机会');
		}
	}
    
    protected function getUserByUsername($username){
        return with(new UserRepository())->addCriterias([
            new FixedCriteria('status', '1'),
            new FixedCriteria('username', $username)
        ])->first();
    }
}